package repository

import (
	"fmt"
	"sync"
)

type Topic struct {
	Id         int64  `gorm:"column:id"`
	UserId     int64  `gorm:"column:user_id"`
	Title      string `gorm:"column:title"`
	Content    string `gorm:"column:content"`
	CreateTime int64  `gorm:"autoCreateTime;column:create_time"`
	ViewCount  int64  `gorm:"column:view_count;default:0"`
}

func (Topic) TableName() string {
	return "topic"
}

type TopicDao struct {
}

var (
	topicDao  *TopicDao
	topicOnce sync.Once
)

func NewTopicDaoInstance() *TopicDao {
	topicOnce.Do(
		func() {
			topicDao = &TopicDao{}
		})
	return topicDao
}

func (*TopicDao) QueryTopicById(id int64) (*Topic, error) {
	var topic Topic
	err := db.Find(&topic, id).Error
	if err != nil {
		fmt.Println("find topic by id err:" + err.Error())
		return nil, err
	}
	return &topic, nil
}

func (*TopicDao) AddTopic(topic *Topic) error {
	ret := db.Create(topic)
	if ret.Error != nil {
		fmt.Println(ret.Error.Error())
	}
	err := ret.Error
	return err
}
